package core

import (
	"bytes"
	"strconv"
	"strings"
	"unicode"
	"unicode/utf8"
)

type CSVBuilder struct {
}

func (builder *CSVBuilder) BuildHeadInfo(row []string, headFix [2]string) *HeadInfo {
	info := new(HeadInfo)
	for k, v := range row {
		cellVal := ParseHeadCellVal(v, headFix)
		var tye string
		var name string
		if cellVal != "" {
			typeAndName := strings.Split(cellVal, ",")
			tye = typeAndName[1]
			name = typeAndName[0]
			info.AddItem(k, tye, name, v)
		} else {
			if v != "" {
				info.AddItem(k, "", "", v)
			}
		}
	}
	return info
}
func (builder *CSVBuilder) GetSaveFileName(fileName string) string {
	return fileName
}
func (builder *CSVBuilder) BuildHeadLine(exportString *bytes.Buffer, saveFileName string, headInfo *HeadInfo) {
	for _, v := range headInfo.Items {
		exportString.WriteString("\"")
		exportString.WriteString(v.CellVal)
		exportString.WriteString("\"")
		exportString.WriteString(",")
	}
	exportString.WriteString("\r\n")
}
func (builder *CSVBuilder) BuildEnd(exportString *bytes.Buffer, headInfo *HeadInfo) {
	// 0
}
func (builder *CSVBuilder) GetID(row []string, headInfo *HeadInfo) string {
	return ""
}
func (builder *CSVBuilder) fieldNeedsQuotes(field string) bool {
	if field == "" {
		return false
	}
	if field == `\.` || strings.ContainsRune(field, ',') || strings.ContainsAny(field, "\"\r\n") {
		return true
	}

	r1, _ := utf8.DecodeRuneInString(field)
	return unicode.IsSpace(r1)
}
func (builder *CSVBuilder) BuildLine(buffer *bytes.Buffer, info *HeadInfo, id string, row []string) {
	for _, item := range info.Items {
		cellVal := row[item.Ix]
		if builder.fieldNeedsQuotes(cellVal) {
			buffer.WriteRune('"')
			for _, r1 := range cellVal {
				switch r1 {
				case '"':
					buffer.WriteString("\"\"")
				case '\r':

				case '\n':

				default:
					buffer.WriteRune(r1)
				}
			}
			buffer.WriteRune('"')
			buffer.WriteRune(',')

			//cellVal = strings.Replace(cellVal, "\"", "\"\"", -1)
			//buffer.WriteString("\"")
			//buffer.WriteString(cellVal)
			//buffer.WriteString("\",")
		} else {
			float, e := strconv.ParseFloat(cellVal, 64)
			if e == nil {
				buffer.WriteString(strconv.FormatFloat(float, 'f', -1, 64))
			} else {
				buffer.WriteString(cellVal)
			}
			buffer.WriteString(",")
		}
	}
	buffer.WriteString("\r\n")
}
